#!/bin/bash
if [ $# -ne 2 ]; then  
    echo "错误：需要指定TS文件和输出TS文件"  
    echo "$0 input.ts output.ts"
    exit 1  
fi 
dir="output"
audiodir="output/audio"
videodir="output/video"
if [ ! -d "$dir" ]; then  
    mkdir $dir
fi
if [ ! -d "$audiodir" ]; then  
    mkdir $audiodir
fi
if [ ! -d "$videodir" ]; then  
    mkdir $videodir
fi

file=$1
#prefix="${file%%.*}"
ffmpeg -loglevel warning -i $1 -vn  -f segment -segment_time 0.0667 -acodec copy -y $audiodir/%03d.aac
ffmpeg -loglevel warning -i $1 -an    $videodir/%03d.png

number=$(ls -lh $videodir/*.png |wc -l)
duration=$(echo "0.0667 * $number" | bc) 
echo "  Duration: 0-$duration"
echo "  输入要剪掉的时间段，比如2.33-6.388"
#!/bin/bash  
read original_string
echo "你输入了: $original_string"
  
IFS="-" read -ra parts <<< "$original_string"  
  
var1=${parts[0]}  
var2=${parts[1]}  
  
start=`printf "%03d\n" $(echo "scale=0; $var1 / 0.0667" | bc)`
stop=`printf "%03d\n" $(echo "scale=0; $var2 / 0.0667" | bc)`
echo "起始分片: $start"
echo "结束分片: $stop"

sleep 1

for part in $(seq $start $stop); do  
    part=`printf "%03d" $part`
    echo "删除音频: $audiodir/$part.aac 删除视频: $videodir/$part.png"
    rm -rf $audiodir/$part.aac
    rm -rf $videodir/$part.png
done

#generate concat, then video.ts
videofiles=`ls $videodir/*.png`
for file in $videofiles;do
   file=`basename $file`
   echo "file '$file'" >>$videodir/concat
   echo "duration 0.066667" >>$videodir/concat
done
ffmpeg -loglevel warning -f concat -i $videodir/concat -c:v libx264 -g 30 -bf 0 -b:v 650k -r 15 -pix_fmt yuv420p  -y $videodir/video.ts


#generate audio.aac
aacfiles=$(ls "$audiodir")
for x in $aacfiles;
do
cat $audiodir/$x >>$audiodir/audio.aac
done

#concat video.ts audio.aac
ffmpeg -loglevel warning -i $videodir/video.ts -i $audiodir/audio.aac -codec copy -y $2

rm -rf $dir/
